﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;

namespace Data
{
   public class DataBase
   {
      private readonly SqlConnection _connection;

      protected DataBase()
      {
          _connection = new SqlConnection("Data Source=.;Initial Catalog=mediaPortal;Integrated Security=True");
      }

     
      protected DataTable ExecuteDataTable(string spName, List<SqlParameter> parameters )
      {
          var cmd = new SqlCommand(spName, _connection); 
          cmd.CommandType = CommandType.StoredProcedure;
          cmd.Parameters.AddRange(parameters.ToArray());

         return ExecuteDataTable(cmd);
      }

      private DataTable ExecuteDataTable(SqlCommand cmd)
      {
          _connection.Open();
          var adapter = new SqlDataAdapter(cmd);
          var dataTable = new DataTable();
          adapter.Fill(dataTable);
          _connection.Close();
          return dataTable;
      }

      protected object ExecuteScalar(string spName, List<SqlParameter> parameters)
      {
          var cmd = new SqlCommand(spName, _connection);
          cmd.CommandType = CommandType.StoredProcedure;
          cmd.Parameters.AddRange(parameters.ToArray());

          return ExecuteScalar(cmd);
      }

      private object ExecuteScalar(SqlCommand cmd)
      {
          _connection.Open();
          var obj = cmd.ExecuteScalar();
          _connection.Close();
          return obj;
      }
      protected void ExecuteNonQuery(string spName, List<SqlParameter> parameters)
      {
          var cmd = new SqlCommand(spName, _connection);
          cmd.CommandType = CommandType.StoredProcedure;
          cmd.Parameters.AddRange(parameters.ToArray());

          _connection.Open();

          cmd.ExecuteNonQuery();

          _connection.Close();

      }




      protected object CheckParametr(object obj)
      {

         try
         {


            int id = Convert.ToInt32(obj);
            decimal rating = Convert.ToDecimal(obj);
            if (id == 0 || rating == 0)
               return null;

         }
         catch
         {
            if (obj == null) return null;

         }
         return obj;

      }

      protected object CheckDbNull(object obj)
      {
         if (obj == DBNull.Value)
            return null;
         return obj;
      }
   }
}